/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.BluetoothChat.activity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothChat.bean.Game;
import com.example.android.BluetoothChat.bean.Player;
import com.example.android.BluetoothChat.constants.IntentConstants;
import com.example.android.BluetoothChat.listener.NewPlayerFoundListener;
import com.example.android.BluetoothChat.service.IGameService;
import com.example.android.BluetoothChat.util.provider.IPlayerProvider;
import com.example.android.BluetoothChat.util.provider.impl.MockGameProviderImpl;
import com.example.android.BluetoothChat.util.provider.player.impl.GlobalPlayerProviderImpl;

/**
 * This is the main Activity that displays the current chat session.
 */
public class PlayerListActivity extends Activity {
	// Debugging
	public static final boolean D = true;


	// Layout Views
	private TextView mTitle;
	private Button _findPlayersButton;

	//service used to get players and games around the device
	IPlayerProvider _globaPlayerProvider = null;

	// service to get games informations
	private IGameService _gameService = new MockGameProviderImpl();

	// model for ListView
	final Set<Player>_playerSet = new HashSet<Player>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		_globaPlayerProvider = new GlobalPlayerProviderImpl();

		if(D) Log.i(getClass().getSimpleName(), "+++ ON CREATE +++");

		// Set up the window layout
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.player_list);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

		// Set up the custom title
		mTitle = (TextView) findViewById(R.id.title_left_text);
		mTitle.setText(R.string.app_name);
		mTitle = (TextView) findViewById(R.id.title_right_text);

	}

	@Override
	public void onStart() {
		super.onStart();
		setupControllers();
		//_globalDiscoveryService.startService(getIntent());
	}

	@Override
	public synchronized void onResume() {
		super.onResume();
		if(D) Log.i(getClass().getSimpleName(), "+++ ON RESUME +++");
	}

	private void setupControllers(){

		final ListView locPlayerListView = (ListView) findViewById(R.id.in);
		_globaPlayerProvider.addNewPlayerFoundListener(new NewPlayerFoundListener() {

			@Override
			public void newPlayerFound(final Player parPlayer) {


				PlayerListActivity.this.runOnUiThread(new Runnable() {
					public void run() {
						_playerSet.add(parPlayer);
						locPlayerListView.setAdapter(new ArrayAdapter<Player>(PlayerListActivity.this,
								R.layout.message, new ArrayList<Player>(_playerSet)));
					}
				});


			}
		});



		_findPlayersButton = (Button) findViewById(R.id.button_findPlayers);
		_findPlayersButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				// clear current list
				_playerSet.clear();

				//ask services to scan for players nearby
				_globaPlayerProvider.findPlayersNearby(PlayerListActivity.this);


			}
		});

		/* Display player details when clicking on an item */
		locPlayerListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int parPosition,
					long arg3) {
				Player locSelectedPlayer = (Player) arg0.getItemAtPosition(parPosition);
				System.err.println(locSelectedPlayer + " selected");
				Intent intent = new Intent(PlayerListActivity.this, PlayerDetailsActivity.class);
				intent.putExtra(IntentConstants.INTENT_PLAYER, locSelectedPlayer);
				startActivity(intent);
			}

		});

		Spinner locSpinner = (Spinner) findViewById(R.id.choose_game_spinner);
		List<Game> locList = _gameService.getInstalledGames();
		locList.add(0, new Game("[All games]", -1L));
		locSpinner.setAdapter(new ArrayAdapter<Game>(this,
				R.layout.message, locList));
	}


	private void showPreferences(){
		startActivity(new Intent(PlayerListActivity.this, MGDPreferencessActivity.class));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.parameters:
			showPreferences();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(D) Log.i(getClass().getSimpleName(), "+++ ON DESTROY +++");
	}
}
